// index.js
require('dotenv').config();
const express = require('express');
const cors = require('cors');

const authRoutes = require('./routes/authRoutes');
const categoryRoutes = require('./routes/categoryRoutes');
const postRoutes = require('./routes/postRoutes');
const uploadRoutes = require('./routes/uploadRoutes');

// 初始化 Express 应用
const app = express();

// 中间件
app.use(cors()); // 允许跨域请求
app.use(express.json()); // 解析 JSON 请求体
app.use(express.urlencoded({ extended: true })); // 解析 URL-encoded 请求体

// 根路由
app.get('/', (req, res) => {
  res.send('Welcome to the Blog API!');
});

// API 路由
app.use('/api/auth', authRoutes);
app.use('/api/categories', categoryRoutes);
app.use('/api/posts', postRoutes);
app.use('/api/upload', uploadRoutes);

// 未找到路由的处理器
app.use((req, res, next) => {
  res.status(404).json({ message: '路由未找到' });
});

// 全局错误处理器
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ message: '服务器发生错误！' });
});

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});